package com.aabte.weather.weartherdata.weather;


import com.aabte.weather.weartherdata.weather.excpetion.WeatherDataNotFoundException;
import com.aabte.weather.weartherdata.weather.excpetion.WeatherDataParseFailException;
import com.aabte.weather.weather.api.dto.WeatherResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        return doGetWeatherData(cityId);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        return doGetWeatherData(cityName);
    }

    private WeatherResponse doGetWeatherData(String cityIdOrCityName) {
        String cacheKey = cityIdOrCityName;
        String responseBody;

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if (StringUtils.isBlank(responseBody = ops.get(cacheKey))) {
            throw new WeatherDataNotFoundException("weather data cache not found. cityIdOrCityName: " + cityIdOrCityName);
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(responseBody, WeatherResponse.class);
        } catch (JsonProcessingException e) {
            throw new WeatherDataParseFailException("weather data parse failed. cityIdOrCityName: " + cityIdOrCityName, e);
        }
    }
}
